package cn.witsky.rtp2ws.util;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

public class HttpUtil {
	private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

	public static JSONObject doGet(String url) {
		JSONObject result = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建HttpGet请求，相当于在浏览器输入地址
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = null;
		try {
			// 执行请求，相当于敲完地址后按下回车。获取响应
			try {
				response = httpclient.execute(httpGet);
				if (response.getStatusLine().getStatusCode() == 200) {
					// 解析响应，获取数据
					String content = EntityUtils.toString(response.getEntity(), "UTF-8");
					result =JSONObject.fromObject(content);
				}
			} catch (Exception e) {
				logger.error("访问" + url + "出现异常:"+e.getMessage());
			}
			// 判断返回状态是否为200

		} finally {
			if (response != null) {
				// 关闭资源
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// 关闭浏览器
			try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	public static JSONObject doPost(String url, JSONObject jsonParam) {
		JSONObject result = null;
		CloseableHttpResponse response = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {		
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity jsonData = new StringEntity(jsonParam.toString());
			httpPost.setEntity(jsonData);
			response = httpclient.execute(httpPost);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				// 解析响应体
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				result =JSONObject.fromObject(content);
			}
		} catch (Exception e) {
			logger.error("访问" + url + "出现异常:"+e.getMessage());
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// 关闭浏览器
			try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;

	}
}
